package com.xiaobingby.common.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.IService;
import com.xiaobingby.common.page.PageParams;
import com.xiaobingby.common.page.Query;
import com.xiaobingby.common.result.R;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.io.Serializable;
import java.util.ArrayList;

/**
 * 顶级 Controller
 * @author XiaoBingBy
 * @date 2018-09-04 15:21
 * @since 1.0
 */
public class BaseController<BaseServiceImpl extends IService<T>, T, PK extends Serializable> {

    @Autowired
    private BaseServiceImpl baseService;

    @ResponseBody
    @RequestMapping("/list")
    public R pageList(@RequestBody PageParams pageParams) {
        ArrayList<Query> querys = pageParams.getQuerys();
        Page<T> page = new Page<T>(pageParams.getCurrent(), pageParams.getPageSize());
        QueryWrapper<T> tQueryWrapper = new QueryWrapper<>();
        if (querys != null) {
            querys.forEach(query -> {
                if ("eq".equals(query.getType()) && StringUtils.isNotEmpty(query.getValue())) {
                    tQueryWrapper.eq(query.getColumn(), query.getValue());
                }
                if ("like".equals(query.getType()) && StringUtils.isNotEmpty(query.getValue())) {
                    tQueryWrapper.like(query.getColumn(), query.getValue());
                }
            });
        }
        IPage<T> retData = baseService.page(page, tQueryWrapper);
        return R.ok(retData);
    }

    // 插入一条记录（选择字段，策略插入）
    @PostMapping
    public R save(@RequestBody T t) {
        boolean result = baseService.save(t);
        return result?R.ok():R.error("插入失败");
    }

    // 根据 ID 删除
    @DeleteMapping
    public R removeById(PK pk) {
        boolean result = baseService.removeById(pk);
        return result?R.ok():R.error("删除失败");
    }

    // 根据 ID 选择修改
    @PutMapping
    public R updateById(T t) {
        boolean result = baseService.updateById(t);
        return result?R.ok():R.error("修改失败");
    }

    // 根据 ID 查询
    @GetMapping("{id}")
    public R getById(@PathVariable PK id) {
        T result = baseService.getById(id);
        return R.ok(result);
    }

}
